// pages/menu/bind-qrcode/bind-qrcode.js
let app = getApp();
let verify = require('../../../utils/verify-token.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceId: '',
    devData:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      deviceId: options.deviceId
    });
    this.getDevInfo();
  },
  getDevInfo(){   
    let token = app.globalData.token;
    let baseUrl = app.globalData.appbaseUrl;
    let deviceId = this.data.deviceId;
    let that = this;
    wx.request({
      url: baseUrl + 'device/' + deviceId +'/info',
      header: {
        'AUTHORIZATION': token
      },
      success: function (res) {
        if (res.data.code == 60006) {
          verify.clearAll()
        } else if (res.data.code == 200) {
          let devdata = res.data.data;
          let objData = { identifier: '', imei: '', mac:'',sim:''};
          for (let key in objData){
            objData[key] = devdata[key];
          }
          that.setData({
            devData:objData
          })
        
        } else {
          wx.showModal({
            title: '操作失败',
            content: res.data.message,
          })
        }
      }
    })

  },
  bindqr(){
    let that = this;
    wx.scanCode({
      success(res) {
        let data = res.result.split("=")
        let qrId = data[1];
        that.bindQr(qrId);
      },
      fail() {
        console.log("扫码失败")
      }
    })
  },
  bindQr(qrId){
    let token = app.globalData.token;
    let baseUrl = app.globalData.appbaseUrl;
    let deviceId = this.data.deviceId;
    let that = this;
    wx.request({
      url: baseUrl + 'device/' + deviceId + '/bind_qr',
      header: {
        'AUTHORIZATION': token,
        'content-type': 'application/x-www-form-urlencoded' 
      },
      method:'PUT',
      data:{
        qrId: qrId
      },
      success: function (res) {
        if (res.data.code == 60006) {
          verify.clearAll()
        } else if (res.data.code == 200) {
          wx.redirectTo({
            url: 'bind-success/bind-success?deviceId='+res.data.data.deviceId,
          })
        } else {
          wx.showModal({
            title: '操作失败',
            content: res.data.message,
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})